/*监控网络线程回调函数，利用信号来接收UDP数据*/
#include 	"ipmsg.h"
#include 	"MyIpmsg.h"

void * watch_net(void * arg)
{
	int 			optval = 1;
	unsigned int 		com;
	struct in_addr 		bcastaddr;
	struct ipmsguser 	* p = NULL;
	ipmsgdata 		* data = NULL;
	
	head = (struct ipmsguser * ) malloc(sizeof(struct ipmsguser));
	
	if (!head) {
		perror("malloc");
		exit(1);
	}
	
	head->next = NULL;
	head->pre = NULL;
	p = head;
	tail = head;
	
	if ( (soc =socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("socket");
		exit(1);
	}
	
	memset( (char * ) ( & me), 0, sizeof(me));
	me.sin_family = AF_INET;
	me.sin_port = htons(ipmsgport);
	me.sin_addr.s_addr = INADDR_ANY;
	
	if ( setsockopt(soc, SOL_SOCKET, SO_BROADCAST, & optval, sizeof(optval)) == -1) {
		perror("setsockopt");
		exit(1);
	}
	
	if ( bind(soc, (struct sockaddr * ) & me, sizeof(me)) == -1) {
		perror("bind");
		exit(1);
	}
	
	if ( gethostname(hostname, HOSTNAME_LENGTH) == -1) {
		perror("gethostname");
		exit(1);
	}
	
	if ( !( user = getenv("USER"))) {
		perror("getenv");
		exit(1);
	}
	
	com = IPMSG_BR_ENTRY;
	
	if (inet_aton(bcastaddrstr, & bcastaddr) == 0) {
		perror("inet_aton");
		exit(1);
	}
	
	memset( (char * ) & bcast, 0, sizeof(bcast));
	bcast.sin_family = AF_INET;
	bcast.sin_port = htons(ipmsgport);
	bcast.sin_addr = bcastaddr;
	ipmsgsendbcast( & bcast, IPMSG_NOOPERATION, data);
	ipmsgsendbcast( & bcast, com, data);
	
	//if( signal(SIGIO, recvfromx) == SIG_ERR)	/*使用信号来监控网络，当收到SIGIO信号时即有数据到达*/
	//	perror("can't catch SIGIO");
	
	/*-----------------------见Unix网络编程(第三版)第一卷576页(对这些调用尚不熟悉)---------------------------------*/
	/*fcntl(soc, F_SETOWN, getpid());
	ioctl(soc, FIOASYNC, & on);
	ioctl(soc, FIONBIO, & on);
	sigemptyset( & zeromask);
	sigemptyset( & oldmask);
	sigemptyset( & newmask);
	sigaddset( & newmask, SIGIO);
	sigprocmask(SIG_BLOCK, & newmask, & oldmask);*/
	/*--------------------------------------------------------------------------------------------------------------*/
	while (1) {
		//recvfrom(soc,buff,8192,0,(struct sockaddr *)&from,&fromlen);	/*此处是否该设计为非阻塞式的IO？*/
		recvfrom(soc, buff, 8192, 0, (struct sockaddr * ) & from, &fromlen);
		data = (ipmsgdata * ) malloc(sizeof(struct ipmsgdata));
		memset(data, 0, sizeof(struct ipmsgdata));
		data->ip = inet_ntoa(from.sin_addr);
		ipmsgswitch(data, buff);
		free(data);
		
		/*if (sendcheckflag) {
			
			time2 = time(NULL);
			
			if( (time2 - time1) > MAXREPEAT)
				repeatflag = 1;			
		}*/
	}
}
/*-----------------------------------信号处理函数---------------------------*/
void recvfromx(int signo)
{
	ipmsgdata * data = NULL;
	
	recvfrom(soc, buff, 8192, 0, (struct sockaddr * ) & from, & fromlen);
	data = (ipmsgdata * ) malloc(sizeof(struct ipmsgdata));
	ipmsgswitch(data, buff);
}
